/*
 * @lc app=leetcode.cn id=199 lang=cpp
 *
 * [199] 二叉树的右视图
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        if(!root) return {};
        
        vector<int> ans;

        vector<TreeNode*> q[2];
        int flag = 0;
        q[flag].push_back(root);

        while(!q[0].empty() || !q[1].empty())
        {
            ans.push_back((*(q[flag].end()-1))->val);

            for(auto p : q[flag])
            {
                if(p->left)
                    q[1-flag].push_back(p->left);
                if(p->right)
                    q[1-flag].push_back(p->right);
            }

            q[flag].clear();
            flag = 1 - flag;

        }

        return ans;
    }
};
// @lc code=end

